package leetcode.newVersion.Hash;

import java.util.HashSet;
import java.util.Set;

public class lc128 {
    public int longestConsecutive(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for (int num : nums) {
            set.add(num);
        }

        int res = 0;
        //判断起点，若set中存在x-1，则跳过x的判断，从x-1开始
        for (int x:set) {
            if (set.contains(x - 1)) {
                continue;
            }

            //找到了这一连续数列的起点，不断向后寻找直到数列结束
            int next=x+1;
            while (set.contains(next)) {
                next++;
            }

            //循环结束后，next-1 是最后一个在哈希集合中的数
            //更新res取值
            res = Math.max(res, next-x);
        }
        return res;
    }

    public static void main(String[] args) {
        lc128 lc128 = new lc128();
        int[] nums1 = {100,4,200,1,3,2};
        int[] nums2 = {0,3,7,2,5,8,4,6,0,1};
        int[] nums3 = {1,0,1,2};

        System.out.println(lc128.longestConsecutive(nums1));
        System.out.println(lc128.longestConsecutive(nums2));
        System.out.println(lc128.longestConsecutive(nums3));
    }
}
